package com.dog.basics.sys.aspect;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.SystemClock;
import com.dog.basics.common.annotation.SysLog;
import com.dog.basics.common.util.IPHelper;
import com.dog.basics.common.util.Json;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.sys.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author dog
 */
@Aspect
@Component
public class SysLogAspect {
    private static Logger logger = LoggerFactory.getLogger(SysLogAspect.class);
    @Autowired
    private SysLogService sysLogService;

    @Around("@annotation(sysLog)")
    public Object around(ProceedingJoinPoint joinPoint, SysLog sysLog) throws Throwable {
        long beginTime = SystemClock.now();
        //执行方法
        Object result = joinPoint.proceed();
        //执行时长(毫秒)
        long time = SystemClock.now() - beginTime;


        com.dog.basics.bean.model.sys.SysLog sysLogEntity = new com.dog.basics.bean.model.sys.SysLog();
        if (sysLog != null) {
            //注解上的描述
            sysLogEntity.setOperation(sysLog.value());
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        sysLogEntity.setMethod(className + "." + methodName + "()");

        //请求的参数
        Object[] args = joinPoint.getArgs();
        if (CollUtil.isNotEmpty(Arrays.asList(args))) {
            String params = Json.toJsonString(args[0]);
            sysLogEntity.setParams(params);
        }

        //设置IP地址
        sysLogEntity.setIp(IPHelper.getIpAddr());

        //用户名
        try {
            String username = SecurityUtils.getSysUser().getUsername();
            sysLogEntity.setUsername(username);
        } catch (Exception ex) {

        }
        sysLogEntity.setTime(time);
        sysLogEntity.setCreateDate(DateUtil.currentSeconds());
        //保存系统日志
        sysLogService.save(sysLogEntity);


        return result;
    }

}
